package utils;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;

import http.ApiUtil;
import http.RequestMapBean;
import log.LogManager;
import utils.common.StringUtils;
import utils.common.TimeUtils;
import utils.common.ToastUtil;

/**
 * 类名称：RequestEncryDecryptUtil
 * 类描述: http的加密 解密工具类
 *
 * @see
 */
public class RequestEncryDecryptUtil {
    private static RequestParams requestParams;

    /**
     * 获取加密密钥
     */
    public static String getSecKey(String token, String returnSecKey) {
        //获取种子
        String subImei = token.substring(5, 10);
        String secKey = AESEncryptUtils.decrypt(returnSecKey, AESEncryptUtils.getSecretKey(subImei));
        return secKey;
    }

    /**
     * uuid
     */
    public static String getSecKey(Context context, String returnSecKey) {
        String uuID = PhoneUtil.getUUID(context);
        //获取种子
        String subImei = uuID.substring(5, 10);
        String secKey = AESEncryptUtils.decrypt(returnSecKey, AESEncryptUtils.getSecretKey(subImei));
        return secKey;
    }
    //  加密******************************************************************************

    /**
     * requestSmssRequestParams 请求下发短信
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static RequestParams requestSmssRequestParams(String phone) {
        String timestamp = FileUtil.getCurMillions();
        //获取加密key
        String timeKey = AESEncryptUtils.getSecretKey(timestamp);

        //拼接sign
        String signStr = ApiUtil.getApiServerPath() + "/sms/sendCode?phone=" + phone.substring(0, 3)+ phone.substring(7, phone.length());
        //对sign进行md5
        String md5Str = AESEncryptUtils.md5String(signStr);
        //AES 加密
        String aesStr = AESEncryptUtils.encrypt(md5Str, timeKey);

        requestParams = getRequestParams();
        requestParams.put("phone", phone);
        requestParams.put("timestamp", timestamp);
        requestParams.put("sign", aesStr);
        String param = new Gson().toJson(requestParams);
        LogManager.getLogger().l("HTTP 请求参数=======>" + param);
        return requestParams;
    }

    /**
     * 注册验证请求参数
     *
     * @param phone
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static RequestParams requestRegisterVerifyRequestParams(String phone) {
        return requestLoginOrRegisterVerifyRequestParams(phone, "sendVoiceCode", null);
    }

    /**
     * 登录验证请求参数
     *
     * @param phone
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static RequestParams requestLoginVerifyRequestParams(String phone, Integer verifyMode) {
        return requestLoginOrRegisterVerifyRequestParams(phone, "sendCodeByLogin", verifyMode);
    }

    /**
     * 登录或注册请求参数
     *
     * @param phone
     * @param type  sign类型 sendVoiceCode：注册语音验证     sendCodeByLogin：登录验证
     * @param verifyMode 登录验证方式 1：语音验证  2：短信验证  null:注册语音验证传null
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static RequestParams requestLoginOrRegisterVerifyRequestParams(String phone, String type, Integer verifyMode) {
        String timestamp = FileUtil.getCurMillions();
        //获取加密key
        String timeKey = AESEncryptUtils.getSecretKey(timestamp);

        //拼接sign
        String signStr = ApiUtil.getApiServerPath() + "/sms/" + type + "?phone=" + phone.substring(0, 3) + phone.substring(7, phone.length());
        //对sign进行md5
        String md5Str = AESEncryptUtils.md5String(signStr);
        //AES 加密
        String aesStr = AESEncryptUtils.encrypt(md5Str, timeKey);

        requestParams = getRequestParams();
        requestParams.put("phone", phone);
        requestParams.put("timestamp", timestamp);
        requestParams.put("sign", aesStr);
        if (null != verifyMode){
            requestParams.put("verifyMode", verifyMode);
        }
        String param = new Gson().toJson(requestParams);
        LogManager.getLogger().l("HTTP 请求参数=======>" + param);
        return requestParams;
    }

    /**
     * requestSmssRequestParams 忘记密码 下发短信
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static RequestParams requestSmssFindPwdCodeRequestParams(String phone) {
        String timestamp = FileUtil.getCurMillions();
        //获取加密key
        String timeKey = AESEncryptUtils.getSecretKey(timestamp);
        if (phone != null && phone.length()<11){
            ToastUtil.showErrorMsg("手机号必须是11位");
        }
        if (TextUtils.isEmpty(phone)){
            ToastUtil.showErrorMsg("手机不能为空");
        }
        //拼接sign
        String signStr = ApiUtil.getApiServerPath() + "/sms/sendFindPwdCode?phone=" + phone.substring(0, 3)
                + phone.substring(7, phone.length());
        //对sign进行md5
        String md5Str = AESEncryptUtils.md5String(signStr);
        //AES 加密
        String aesStr = AESEncryptUtils.encrypt(md5Str, timeKey);

        requestParams = getRequestParams();
        requestParams.put("phone", phone);
        requestParams.put("timestamp", timestamp);
        requestParams.put("sign", aesStr);
        return requestParams;
    }

    /**
     * registerPhonerRequestParams  手机号码注册
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static RequestParams registerPhonerRequestParams(String uuid, String returnSecKey, String phone, String pwd,
                                                            String randomNum) {
        //密码 md5
        String md5pwd = AESEncryptUtils.md5String(pwd);

        String reg = "phone=" + phone + "|pwd=" + md5pwd + "|randomNum=" + randomNum;
        //对参数列表加密
        reg = AESEncryptUtils.encrypt(reg, returnSecKey);

        requestParams = getRequestParams();
        requestParams.put("pim", uuid);
        requestParams.put("para", reg);
        return requestParams;
    }

    /**
     * registerPhonerRequestParams  修改用户密码(忘记密码)
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static RequestParams updatePhonerRequestParams(String uuid, String returnSecKey, String phone, String pwd,
                                                          String randomNum) {
        //密码 md5
        String md5pwd = AESEncryptUtils.md5String(pwd);

        String reg = "phone=" + phone + "|pwd=" + md5pwd + "|seeds=" + randomNum;
        //对参数列表加密
        reg = AESEncryptUtils.encrypt(reg, returnSecKey);

        requestParams = getRequestParams();
        requestParams.put("pim", uuid);
        requestParams.put("para", reg);
        return requestParams;
    }

    /**
     * loginPhoneRequestParams  帐号登录
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static RequestParams loginPhoneRequestParams(Context context, String para) {
        String uuID = PhoneUtil.getUUID(context);

        para = AESEncryptUtils.encrypt(para, uuID);

        requestParams = getRequestParams();
        requestParams.put("pim", uuID);
        requestParams.put("para", para);
        return requestParams;
    }

    /**
     * loginPhoneRequestParams  帐号登录
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static RequestParams loginPhoneRequestParams(Context context, String returnSecKey, String phone, String pwd) {
        String uuID = PhoneUtil.getUUID(context);
        //密码 md5
        String md5pwd = AESEncryptUtils.md5String(pwd);

        String reg = "username=" + phone + "|pwd=" + md5pwd;
        LogManager.getLogger().l("reg ====>" + reg);
        //对参数列表加密
        reg = AESEncryptUtils.encrypt(reg, returnSecKey);

        requestParams = getRequestParams();
        requestParams.put("pim", uuID);
        requestParams.put("para", reg);
        return requestParams;
    }

    /**
     * 帐号登录验证
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static RequestParams loginPhoneVerifyRequestParams(Context context, String returnSecKey, String phone, String pwd, String randomNum) {
        RequestMapBean requestMap = new RequestMapBean();

        String uuID = PhoneUtil.getUUID(context);
        //密码 md5
        String md5pwd = AESEncryptUtils.md5String(pwd);

        requestMap.put("phone",phone);
        requestMap.put("pwd",md5pwd);
        requestMap.put("randomNum",randomNum);

        String reg = new Gson().toJson(requestMap);

        LogManager.getLogger().l("reg ====>" + reg);
        //对参数列表加密
        reg = AESEncryptUtils.encrypt(reg, returnSecKey);

        requestParams = getRequestParams();
        requestParams.put("pim", uuID);
        requestParams.put("para", reg);
        return requestParams;
    }

    /**
     * loginPhoneRequestParams  第三方登录
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static RequestParams loginThirdRequestParams(Context context, String bundType, String thrOpenId,
                                                        String secKey) {
        String uuID = PhoneUtil.getUUID(context);

        String reg = "bundType=" + bundType + "|thrOpenId=" + thrOpenId;
        //对参数列表加密
        reg = AESEncryptUtils.encrypt(reg, secKey);

        requestParams = getRequestParams();
        requestParams.put("pim", uuID);
        requestParams.put("para", reg);
        return requestParams;
    }

    /**
     * commonRequestParams  常规请求
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static RequestParams commonRequestParams(Context context, RequestMapBean requestMap) {
        String uuID = PhoneUtil.getUUID(context);
        String userid = SharedPreUtil.getInstance(context).getValue(SharedPreUtil.USER_ID);
        String token = SharedPreUtil.getInstance().getValue(SharedPreUtil.USER_TOKEN);
        String timestamp = FileUtil.getCurMillions();

        Long id = "".equals(userid) ? 0 : Long.parseLong(userid);//判空
        String sign = AESEncryptUtils.md5String("userId=" + id + "&timestamp=" + timestamp + "&token=" + token);

        StringBuffer buf = new StringBuffer();
        for (String key : requestMap.keySet()) {
            buf.append(key + "=" + requestMap.get(key));
            buf.append("|");
        }
        LogManager.getLogger().l("HTTP 请求参数=======>" + buf.toString());
        buf.deleteCharAt(buf.length() - 1);
        String reg = AESEncryptUtils.encrypt(buf.toString(), AESEncryptUtils.getSecretKey(token));

        requestParams = getRequestParams();
        requestParams.put("userId", id);
        requestParams.put("timestamp", timestamp);
        requestParams.put("sign", sign);
        requestParams.put("para", reg);
        requestParams.put("pim", uuID);
        return requestParams;
    }

    /**
     * commonRequestParams  常规请求  json格式
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    public static RequestParams commonJsonRequestParams(Context context, RequestMapBean requestMap) {
        String uuID = PhoneUtil.getUUID(context);
        String userid = SharedPreUtil.getInstance(context).getValue(SharedPreUtil.USER_ID);
        String token = SharedPreUtil.getInstance().getValue(SharedPreUtil.USER_TOKEN);
        String timestamp = TimeUtils.getCurrentTime()+"";//FileUtil.getCurMillions();

        String sign = AESEncryptUtils.md5String("userId=" + userid + "&timestamp=" + timestamp + "&token=" + token);
        LogManager.getLogger().l("sign =======>" + sign);
        String param = new Gson().toJson(requestMap);
        LogManager.getLogger().l("HTTP 请求参数=======>" + param);
        String reg = AESEncryptUtils.encrypt(param, AESEncryptUtils.getSecretKey(token));

        requestParams = getRequestParams();
        requestParams.put("userId", userid);
        requestParams.put("timestamp", timestamp);
        requestParams.put("sign", sign);
        requestParams.put("para", reg);
        requestParams.put("pim", uuID);

        return requestParams;
    }

    private static RequestParams getRequestParams() {
        String version = SharedPreUtil.getInstance().getValue(SharedPreUtil.VERSION_NAME);
        requestParams = new RequestParams();
        requestParams.put("version", version);
        requestParams.put("terminal", "1");
        return requestParams;
    }

    //  解密******************************************************************************
    //对请求返回的data进行解密
    public static String decryptBackData(Context context, String data) {
        if (!StringUtils.isEmpty(data)) {
            String token = SharedPreUtil.getInstance(context).getValue(SharedPreUtil.USER_TOKEN);
            LogManager.getLogger().i("HTTP 请求参数=======>token", token);
            if(token.equals("")){
                return null;
            }
            return getSecKey(token, data);
        } else {//为空字符直接返回
            return data;
        }
    }
}
